package com.furongji.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.furongji.common.domain.vo.UserSimpleVo;
import com.furongji.common.enums.CommentStatusEnum;
import com.furongji.common.enums.CommentTargetTypeEnum;
import com.furongji.common.utils.UserThreadLocalUtil;
import com.furongji.education.clients.UserFeignClient;
import com.furongji.education.domain.dto.CommentDto;
import com.furongji.education.domain.po.Comment;
import com.furongji.education.domain.vo.CommentVo;
import com.furongji.education.mapper.CommentMapper;
import com.furongji.education.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 通用评论表 服务实现类
 * </p>
 *
 * @author furongji
 * @since 2025-06-03
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final UserFeignClient userClient;

    @Override
    public IPage<CommentVo> getCommentsByTarget(Integer current, Integer size, String targetId, CommentTargetTypeEnum targetType) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getTargetId, targetId)
                .eq(Comment::getTargetType, targetType)
                .eq(Comment::getParentId, "0")
                .eq(Comment::getStatus, CommentStatusEnum.VISIBLE)
                .orderByDesc(Comment::getGmtCreate);
        IPage<Comment> rootPage = baseMapper.selectPage(new Page<>(current, size), queryWrapper);
        // 获得主评论
        List<Comment> rootComments = rootPage.getRecords();
        // 获提取主评论Id列表
        List<String> rootIds = rootComments.stream()
                .map(Comment::getId)
                .toList();

        // 获得所有子评论
        List<Comment> childComments = new ArrayList<>();
        if (!rootIds.isEmpty()) {
            LambdaQueryWrapper<Comment> childWrapper = new LambdaQueryWrapper<>();
            childWrapper.in(Comment::getParentId, rootIds)
                    .eq(Comment::getStatus, 1)
                    .orderByAsc(Comment::getGmtCreate);
            childComments = baseMapper.selectList(childWrapper);
        }

        // 对子评论Vo进行分组
        Map<String, List<CommentVo>> childrenMap = childComments.stream()
                .map(c -> {
                    CommentVo vo = new CommentVo();
                    BeanUtils.copyProperties(c, vo);
                    // 远程调用
                    UserSimpleVo userSimpleVo = userClient.getNameAndAvatar(vo.getUserId());
                    vo.setUsername(userSimpleVo.getUsername());
                    vo.setAvatar(userSimpleVo.getAvatar());
                    vo.setIsLike(false); //TODO 后期加入点赞功能
                    return vo;
                })
                .collect(Collectors.groupingBy(CommentVo::getParentId));

        // 子评论Vo添加到主评论Vo中的list
        List<CommentVo> resultList = rootComments.stream().map(root -> {
            CommentVo vo = new CommentVo();
            BeanUtils.copyProperties(root, vo);

            UserSimpleVo userSimpleVo = userClient.getNameAndAvatar(vo.getUserId());
            vo.setUsername(userSimpleVo.getUsername());
            vo.setAvatar(userSimpleVo.getAvatar());

            vo.setIsLike(false); //TODO 后期加入点赞功能
            vo.setChildren(childrenMap.getOrDefault(root.getId(), new ArrayList<>()));
            return vo;
        }).toList();

        Page<CommentVo> resultPage = new Page<>();
        resultPage.setRecords(resultList);
        resultPage.setTotal(rootPage.getTotal());
        resultPage.setCurrent(rootPage.getCurrent());
        resultPage.setSize(rootPage.getSize());
        resultPage.setPages(rootPage.getPages());

        return resultPage;
    }

    @Override
    public boolean saveCommentByTarget(CommentDto commentDto) throws JsonProcessingException {
        String content = commentDto.getContent();
        String targetId = commentDto.getTargetId();
        CommentTargetTypeEnum targetType = commentDto.getTargetType();
        String parentId = commentDto.getParentId();
//        System.out.println(UserThreadLocalUtil.getUser());
        if (StringUtils.isEmpty(parentId)) {
            parentId = "0";
        }
        String userId = new ObjectMapper()
                .readTree(UserThreadLocalUtil.getUser())
                .get("userId")
                .asText();
//        System.out.println("userId: " + userId);
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setTargetId(targetId);
        comment.setTargetType(targetType);
        comment.setParentId(parentId);
        comment.setUserId(userId);

        return super.save(comment);
    }
}
